Categories
React Hooks

Top React Hooks — States and Requests

Spread the love

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

Hookstate

We can use the Hookstate hook to change global and local state in our app.

To use it, we run:

npm install --save @hookstate/core

or:

yarn add @hookstate/core

to install it.

Then we can manage global state by writing:

import React from "react";
import { createState, useState } from "@hookstate/core";
const globalState = createState(0);

export default function App() {
  const state = useState(globalState);
  return (
    <>
      <p>Counter value: {state.get()}</p>
      <button onClick={() => state.set(p => p + 1)}>Increment</button>
    </>
  );
}

We create a global state object with the createState function and then pass it into the Hookstate’s useState hook.

Then we can use get and set to get and set the state respectively.

To change local state, we can write:

import React from "react";
import { useState } from "@hookstate/core";

export default function App() {
  const state = useState(0);
  return (
    <>
      <p>Counter value: {state.get()}</p>
      <button onClick={() => state.set(p => p + 1)}>Increment</button>
    </>
  );
}

The only difference is that we pass the state value straight into the useState hook.

States can be nested.

For example, we can write:

import React from "react";
import { useState, self } from "@hookstate/core";

export default function App() {
  const state = useState([{ name: "Untitled" }]);

console.log(state);
  return (
    <>
      {state.map((task, index) => (
        <p>
          {task.name.get()} {index}
        </p>
      ))}
      <button onClick={() => state[self].merge([{ name: "Untitled" }])}>
        add task
      </button>
    </>
  );
}

We use the useState hook with an array.

To add new value to the array, we use the state[self] object’s merge method to add an entry to it.

Then we can get the entry by using the property’s get method as we did in the map callback.

We can also add scoped, async, and recursive states.

We can use the @jzone/react-request-hook to help us make requests easier.

We can install it by running:

npm install @jzone/react-request-hook

or:

yarn add @jzone/react-request-hook

Then we can use it by writing:

import React from "react";
import useFetchData from "@jzone/react-request-hook";
import axios from "axios";

export default function App() {
  const [{ data, isLoading, error }, fetchData] = useFetchData(data =>
    axios.get("https://api.agify.io/?name=michael", { params: data })
  );

  React.useEffect(() => {
    fetchData();
  }, [fetchData]);

  if (!data) {
    return !error ? <div>loading...</div> : <div>error</div>;
  }

  return (
    <div>
      <p>{JSON.stringify(data)}</p>
    </div>
  );
}

We imported the useFetchData hook to import the hook.

Also, we installed Axios to use that as an HTTP client.

Then we use the fetchData function returned by the hook to get the data.

The data has the response data.

So we can render that the way we want.

It also returns the isLoading state to indicate loading.

error has the error.

We can customize it for other kinds of requests.

Conclusion

Hookstate is a useful hook for managing states.

@jzone/react-request-hook is a hook that lets us get data easier.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *